package com.cloudcc.mobile.view.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ResultCallBack;
import com.cloudcc.cloudframe.ui.viewgroup.HorizontalListView;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrClassicFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrDefaultHandler;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrHandler;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.TmVerticalTimelineAdapter;
import com.cloudcc.mobile.dao.impl.ApprovalEngineImpl;
import com.cloudcc.mobile.entity.approval.TaskApprovalHistoryModel;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.view.web.CloudWebViewActivity;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy;
import com.cloudcc.mobile.view.web.WebSyncDefaultProxy.MonitorParam;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 审批(待办任务详细)
 * 
 * @author lhy
 * @date 2015/12/09/17:00
 */
public class TaskManagementHistoryActivty extends BaseActivity implements
		OnClickListener, ResultCallBack<List<TaskApprovalHistoryModel>> {
	private ApprovalEngineImpl engine = new ApprovalEngineImpl();
	private ArrayList<TaskApprovalHistoryModel> modellist2;
	private TmVerticalTimelineAdapter vadapter;
	private String ACTION = "com.cloudcc.mobile.syncWeb";
	private String objecttype;
	private String relatedId;
	private String workItemId;
	private String titlestr;
	@Bind(R.id.bar_back)
	ImageView back;
	@Bind(R.id.bar_title_text)
	TextView title;
	@Bind(R.id.bar_button_plus)
	ImageView imgplus;
	@Bind(R.id.mat_approvaltitle)
	TextView approvaltitle;
	@Bind(R.id.horizontal_timeline)
	HorizontalListView horizontal;
	@Bind(R.id.vertical_timeline)
	ListView vertical;
	@Bind(R.id.again_allocation)
	// 重新分配
	LinearLayout allocation;
	@Bind(R.id.going_approval)
	// 进行审批
	LinearLayout approval;
	@Bind(R.id.task_statuslist_loadmore)
	PtrClassicFrameLayout mptrframe;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		back.setOnClickListener(this);
		imgplus.setVisibility(View.GONE);
		initframe();
		initadapter();
		intidata();
		allocation.setOnClickListener(this);
		approval.setOnClickListener(this);
		initReceiver();
	}

	public void intidata() {
		Intent intent = getIntent();
		objecttype = intent.getStringExtra("objecttype");
		relatedId = intent.getStringExtra("relatedId");
		titlestr = intent.getStringExtra("title");
		if (objecttype == null) {
			approvaltitle.setVisibility(View.GONE);
		} else {
			approvaltitle.setText(objecttype);
		}
		title.setText(titlestr);
	}

	public void initReceiver() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION);
		registerReceiver(receiver, intentFilter);
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(ACTION)) {
				TaskManagementHistoryActivty.this.finish();
			}
		}
	};

	public void initframe() {
		mptrframe.setLastUpdateTimeRelateObject(this);
		mptrframe.setPtrHandler(new PtrHandler() {
			@Override
			public boolean checkCanDoRefresh(PtrFrameLayout frame,
					View content, View header) {
				return PtrDefaultHandler.checkContentCanBePulledDown(frame,
						vertical, header);
			}

			@Override
			public void onRefreshBegin(PtrFrameLayout frame) {
				refreshData();
			}
		});
		mptrframe.setLoadingMinTime(1000);
		mptrframe.setDurationToClose(200);
		mptrframe.setDurationToCloseHeader(1000);
		mptrframe.setResistance(1.7f);
		mptrframe.setRatioOfHeaderHeightToRefresh(1.2f);
		mptrframe.setPullToRefresh(false);
		mptrframe.setKeepHeaderWhenRefresh(true);
		mptrframe.postDelayed(new Runnable() {
			@Override
			public void run() {
				mptrframe.autoRefresh();
			}
		}, 150);
	}

	public void initadapter() {
		vadapter = new TmVerticalTimelineAdapter(this);
		vertical.setAdapter(vadapter);
	}

	public void refreshData() {
		modellist2 = new ArrayList<TaskApprovalHistoryModel>();
		modellist3 = new ArrayList<>();
		engine.getApprovalHistory(relatedId, this);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}

	@Override
	public int getLayoutId() {
		// TODO Auto-generated method stub
		return R.layout.management_approval_typehistory;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bar_back:
			TaskManagementHistoryActivty.this.finish();
			break;
		case R.id.again_allocation:
			Intent intent = new Intent(mContext, CloudWebViewActivity.class);
			intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
					.getReallocate(workItemId, relatedId));
			MonitorParam monitorParam = new MonitorParam(
					new String[] { "WeiXin_reassignWorkitem.action" },
					WebSyncDefaultProxy.STEP_START,
					new String[] { "WeiXin_index.action" }, true,
					WebSyncDefaultProxy.STEP_FINISH);
			intent.putExtra("callback",
					WebSyncDefaultProxy.creatDefaultProxy(ACTION)
							.addMonitorParam(monitorParam).addHomeMonitor());
			startActivity(intent);
			break;
		case R.id.going_approval:
			Intent intent1 = new Intent(mContext, CloudWebViewActivity.class);
			intent1.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
					.getGoApproval(workItemId, relatedId));
			MonitorParam monitorParam2 = new MonitorParam(new String[] {
					"/WeiXin_processApproval.action", "allocationSp.action" },
					WebSyncDefaultProxy.STEP_START,
					new String[] { "WeiXin_index.action" }, true,
					WebSyncDefaultProxy.STEP_FINISH);
			intent1.putExtra("callback",
					WebSyncDefaultProxy.creatDefaultProxy(ACTION)
							.addMonitorParam(monitorParam2).addHomeMonitor());
			startActivity(intent1);
			break;
		default:
			break;
		}
	}

	@Override
	public void onFailure(ErrorInfo error) {
		// TODO Auto-generated method stub
		Toast.makeText(TaskManagementHistoryActivty.this, "加载失败，请重试",
				Toast.LENGTH_SHORT).show();
		mptrframe.refreshComplete();
	}
	private ArrayList<TaskApprovalHistoryModel.Instancehis> modellist3;
	@Override
	public void onSuccess(List<TaskApprovalHistoryModel> t) {
		// TODO Auto-generated method stub
		for (TaskApprovalHistoryModel taskApprovalHistoryModel : t) {
			modellist2.add(taskApprovalHistoryModel);
		}
		boolean isvisible = false;
		for (int i=0;i<modellist2.size();i++){
			for (int j=0;j<modellist2.get(i).getInstancehis().size();j++){
				modellist3.add(modellist2.get(i).getInstancehis().get(j));
			}
		}

		vadapter.changeData(modellist3);
		if (modellist2.size() > 0) {
			workItemId = modellist2.get(0).getInstancehis().get(0).workitemId;
			String workItemId1 = modellist2.get(0).getInstancehis().get(0).workItemId;
			if (StringUtils.isEmpty(workItemId)) {
				if (StringUtils.isEmpty(workItemId1)) {
					isvisible = false;
				} else {
					workItemId = workItemId1;
					isvisible = true;
				}

			} else {
				isvisible = true;
			}
		} else {
			isvisible = false;
		}
		if (isvisible && objecttype != null) {
			allocation.setVisibility(View.VISIBLE);
			approval.setVisibility(View.VISIBLE);
		} else {
			allocation.setVisibility(View.GONE);
			approval.setVisibility(View.GONE);
		}
		mptrframe.refreshComplete();
	}

}
